/**
 * 个人所得税导入
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { Button, Form, Spin } from 'antd';
import { formatMessage } from 'umi';

import Pagination from '@/components/Pagination';
import { SearchInput } from '@/components/UserForm';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganizationSelect from '@/components/OrganizationSelect';
import { withRoutePage } from '@/utils/enhanceUtils';
import { isSuccess } from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';

import { getSalaryPayrollTaxStatus } from '@/services/salaryManage/salaryCalculate';
import { goToSalaryPayrollTaxEdit, goToSalaryPayrollTaxLog } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import ExcelUploader from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/ExcelUploader';
import SalaryConfigTipPage from '@/pages/SalaryManage/components/SalaryConfigTipPage';
import SummaryTable from '@/components/SummaryTable';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import useHistoryBlock from '@/pages/SalaryManage/hooks/useHistoryBlock';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/index.less';
import ImportExcelRouter from '../component/ImportExcelRouter';
import ImportExcelMenuFilter from '../component/ImportExcelMenuFilter';

const SearchForm = Form.create()(({ form, searchModel, onChange, organizationCode }) => {
    const { getFieldDecorator } = form;

    return (
        <Form layout="inline">
            <Form.Item label="员工" className={salaryStyle.flex} style={{ width: '280px' }}>
                {getFieldDecorator('employeeCode', {
                    ...(searchModel?.employeeCode ? { initialValue: searchModel.employeeCode } : {})
                })(
                    <SearchInput
                        params={{
                            organizationCode
                        }}
                        getData={async params => {
                            if (!params.organizationCode) {
                                return [];
                            }
                            const employeeResponse = await queryEmployeeList({
                                organizationCode: params.organizationCode
                            });
                            return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                        }}
                        selectProps={{
                            placeholder: '请输入员工姓名',
                            allowClear: true
                        }}
                        fieldsName={{
                            value: 'employeeCode',
                            title: 'name'
                        }}
                        onChange={onChange}
                        style={{ width: '220px' }}
                    />
                )}
            </Form.Item>
        </Form>
    );
});

const SalaryPayrollTax = ({
    columns,
    dataSource,
    rowKey,
    pagination,
    loading,
    pageLoading,
    showImportDialog,
    uploadAction,
    showTemplateButton,
    user,
    dispatchType,
    dispatch,
    uploadExtra,
    uploadExtraParams,
    searchModel,
    history,
    selectOrganizationCode,
    organizationResponse
}) => {
    const [canImport, setCanImport] = useState(false);

    const {
        initType,
        tablePageChangeType,
        searchType,
        showImportDialogType,
        deleteType,
        mergeSearchModelType
    } = dispatchType;

    const tablePageChange = ({ current, pageSize }) => {
        dispatch({
            type: tablePageChangeType,
            payload: { current, pageSize }
        });
    };

    const importExcel = () => {
        dispatch({
            type: showImportDialogType,
            payload: true
        });
    };

    const operateAction = {
        onEdit(record) {
            goToSalaryPayrollTaxEdit(record);
        },
        onDelete(record) {
            dispatch({
                type: deleteType,
                payload: record.id,
                currentRecord: record
            });
        }
    };

    useEffect(() => {
        if (selectOrganizationCode) {
            dispatch({ type: initType, payload: { organizationCode: selectOrganizationCode, needReset: true } });
        }
    }, [selectOrganizationCode]);

    const onChange = useCallback(employeeCode => {
        dispatch({
            type: mergeSearchModelType,
            payload: { employeeCode }
        });
        dispatch({
            type: searchType
        });
    }, []);

    useHistoryBlock(history, (/* location, unBlock */) => {
        dispatch({
            type: showImportDialogType,
            payload: false
        });
    });

    useEffect(() => {
        if (selectOrganizationCode) {
            getSalaryPayrollTaxStatus(selectOrganizationCode).then(response => {
                if (isSuccess(response)) {
                    // 0能导入，1不能导入
                    setCanImport(response.data !== 1);
                }
            });
        }
    }, [selectOrganizationCode]);

    const searchNode = useMemo(
        () => (
            <SearchForm
                searchModel={searchModel}
                user={user}
                onChange={onChange}
                organizationCode={selectOrganizationCode}
            />
        ),
        [searchModel, user, onChange, selectOrganizationCode]
    );

    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                dispatch({
                    type: 'importExcelModel/setMultiStore',
                    payload: {
                        selectOrganizationCode: value,
                        countryNameCode: null
                    }
                });
            }
        },
        [selectOrganizationCode]
    );

    useHandleRefreshMessage();

    return (
        <PageHeaderWrapper type="success">
            <ImportExcelMenuFilter>
                <ImportExcelRouter
                    type="salaryExcelImport"
                    extraButton={
                        <div style={{ display: 'flex' }}>
                            <div className={salaryStyle.mr12} style={{ display: 'flex' }}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    onChange={handleOrganizationChange}
                                    value={selectOrganizationCode}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                    treeDataFromProp
                                    treeDataList={organizationResponse}
                                />
                            </div>
                            <div>
                                <Button onClick={() => goToSalaryPayrollTaxLog(selectOrganizationCode)}>
                                    操作日志
                                </Button>
                            </div>
                        </div>
                    }
                >
                    <SalaryConfigTipPage organizationCode={selectOrganizationCode}>
                        <Spin spinning={pageLoading}>
                            <div className={styles.salaryExcelBox}>
                                <TwoColHead
                                    left={searchNode}
                                    right={
                                        <AuthComponent code="finance:salary:computation:import:taxinit:import">
                                            <Button type="primary" onClick={importExcel} disabled={!canImport}>
                                                {/* 导入 */ formatMessage({ id: 'importExcel.import' })}
                                            </Button>
                                        </AuthComponent>
                                    }
                                />
                                <div className={styles.tableBox}>
                                    <SummaryTable
                                        layout="fixed"
                                        bordered
                                        columns={
                                            typeof columns === 'function' ? columns(pagination, operateAction) : columns
                                        }
                                        rowKey={rowKey}
                                        dataSource={dataSource}
                                        pagination={false}
                                        loading={loading.effects[searchType]}
                                        vvSummaryFields={[
                                            'encryptTotalIncomeAmt',
                                            'encryptTotalNotaxAmt',
                                            'encryptTotalTaxIncomeAmt',
                                            'encryptTotalPayedTaxAmt',
                                            'encryptTotalFundOldAmt',
                                            'encryptTotalFundUnemployAmt',
                                            'encryptTotalFundHospitalAmt',
                                            'encryptTotalFundHarmBaseAmt',
                                            'encryptTotalFundBirthBaseAmt',
                                            'encryptTotalFundHouseAmt',
                                            'encryptCurrChildEducationAmt',
                                            'encryptCurrContinueEducationAmt',
                                            'encryptCurrHouseLoanInterestAmt',
                                            'encryptCurrHouseLeaseAmt',
                                            'encryptTotalExpenseAmt',
                                            'encryptCurrRaiseOldAmt',
                                            'encryptTotalAfterTaxAmt'
                                        ]}
                                    />
                                </div>
                                <Pagination {...pagination} onChange={tablePageChange} />
                            </div>

                            <ExcelUploader
                                showImportDialog={showImportDialog}
                                uploadAction={uploadAction}
                                dispatchType={dispatchType}
                                dispatch={dispatch}
                                showTemplateButton={showTemplateButton}
                                user={user}
                                extra={uploadExtra}
                                extraParams={uploadExtraParams}
                            />
                        </Spin>
                    </SalaryConfigTipPage>
                </ImportExcelRouter>
            </ImportExcelMenuFilter>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ salaryPayrollTaxModel, loading, user, importExcelModel }) => ({
        ...salaryPayrollTaxModel,
        selectOrganizationCode: importExcelModel.selectOrganizationCode,
        organizationResponse: importExcelModel.organizationResponse,
        loading,
        dispatchType: {
            initType: 'salaryPayrollTaxModel/init',
            changePeriodType: 'salaryPayrollTaxModel/changePeriod',
            searchType: 'salaryPayrollTaxModel/search',
            deleteType: 'salaryPayrollTaxModel/deleteSalaryPayrollTax',
            tablePageChangeType: 'salaryPayrollTaxModel/tablePageChange',
            showImportDialogType: 'salaryPayrollTaxModel/showImportDialog',
            downloadTemplateType: 'salaryPayrollTaxModel/downloadTemplate',
            setMultiStoreType: 'salaryPayrollTaxModel/setMultiStore',
            mergeSearchModelType: 'salaryPayrollTaxModel/mergeSearchModel'
        },
        showTemplateButton: true,
        templateUrl: '/api/finance/salary/v1/template/excels/taxTemplate',
        uploadAction: `/api/finance/salary/v1/salaryPayrollTax/import/${importExcelModel.selectOrganizationCode}`,
        importAuthCode: 'finance:salary:computation:import:taxinit:import',
        user
    }))(SalaryPayrollTax)
);
